package com.cf.data.serve.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * @author cuixi
 * @description: 百度图片物体识别api
 * @date 2024/11/4
 */
public class BaiduRebarTestUtils {
    public static final String API_KEY = "vJll3550n62YavVWXr2THSfC";
    public static final String SECRET_KEY = "FvDba21vtw3ZgGmiRjE3KA1gwtrfQBvg";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String[] args) throws IOException {
        String imagePath = "C:\\Users\\Administrator\\Pictures\\钢筋训练\\OIP-C (1).png";
        String imagePath2 = "C:\\Users\\Administrator\\Pictures\\钢筋训练\\OIP-C (1)222.png";
        getImageCount(imagePath, imagePath2);
    }

    /**
     * 获取图片内钢筋数量
     * @author cuixi
     * @date 2024/11/5
     * @param imagePath 分析图片地址
     * @param imagePath2 生成框选图片地址
     */
    public static void getImageCount(String imagePath,String imagePath2) {

        MediaType mediaType = MediaType.parse("application/json");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\test.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        String fileContentAsBase64 = null;
        try {
            fileContentAsBase64 = getFileContentAsBase64(imagePath, false);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("image", fileContentAsBase64);
            RequestBody body = RequestBody.create(mediaType, jsonObject.toJSONString());
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/cf_reinforcement?input_type=&access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = null;
            response = HTTP_CLIENT.newCall(request).execute();

            JSONObject result = JSONObject.parseObject(response.body().string());
            JSONArray results = result.getJSONArray("results");
            System.out.println("==获取匹配的数据量==" + results.size());

            //-------------绘制框----------------
            BufferedImage image = ImageIO.read(new File(imagePath));
            Graphics g = image.getGraphics();
            //画笔颜色
            g.setColor(Color.RED);
            for (Object o : results) {
                JSONObject js = JSONObject.parseObject(String.valueOf(o));
                JSONObject location = js.getJSONObject("location");
//            System.out.println("绘制框==="+location.toString());
                //矩形框(原点x坐标，原点y坐标，矩形的长，矩形的宽)
                g.drawRect(location.getIntValue("left"), location.getIntValue("top"), location.getIntValue("height"), location.getIntValue("width"));
            }
            //输出图片的地址
            FileOutputStream out = new FileOutputStream(imagePath2);
            ImageIO.write(image, "jpeg", out);
            System.out.println("===结束导出绘制图===");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }
}
